"""
IOT www.hanxiaoxin.cn:8081 http服务
"""

from lib.net.index import http
from utils import device


def upload_server_log(data, value=None, topic_id="Tiot_ce0sv20g"):
    """
    记录服务器启动状态
    """
    if value is None:
        value = {}
    payload = {
        "op": "upload",
        "name": "dataset",
        "topic": topic_id,
        "data": data,
        "device_id": device.get_id(),
        "value": value,
        "extra": {
            "device_info": device.get_info(),
        },
    }
    # print(f"upload data to iot topic-{topic_id}")
    resp = http.POST("http://www.hanxiaoxin.cn:8081/iot/upload", payload)
    # print(resp)
    return resp


def upload_data(data, topic_id="Tiot_bba1471x", value=None):
    """
    上传数据
    topic_id: 表ID
    data: 字符串, 逗号分隔
    value: Dict json
    """
    if value is None:
        value = {}
    payload = {
        "op": "upload",
        "name": "dataset",
        "topic": topic_id,
        "data": data,
        "device_id": device.get_id(),
        "value": value,
        "extra": {
            "device_info": device.get_info(),
        },
    }
    # print(f"upload data to iot topic-{topic_id}")
    resp = http.POST("http://www.hanxiaoxin.cn:8081/iot/upload", payload)
    # print(resp)
    return resp


def create_topic(name="micropython_table", description="auto create"):
    """
    新建TOPIC
    """
    payload = {
        "name": name,
        "columns": [
            {"name": "时间", "type": "STRING"},
            {"name": "数据1", "type": "STRING"},
        ],
        "description": description,
    }
    print("create iot table")
    resp = http.POST("http://www.hanxiaoxin.cn:8081/iot/table", payload)
    # print(resp)
    return resp
